/**
 * 
 */
package com.preop.json.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;

/**
 * @author klevak
 * 
 */
public class ConvertXMltoJson {


	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) {

		// We need to convert this xml to JSON


		String xmlDir = "../preop/WebContent/xml/";
		String jsonDir = "../preop/WebContent/json/";
		convertXmlFileDir(xmlDir,jsonDir);
		
		xmlDir = "../preop/WebContent/xml/partners/";
		jsonDir = "../preop/WebContent/json/partners/";
		convertXmlFileDir(xmlDir,jsonDir);

		xmlDir = "../preop/WebContent/xml/center/";
		jsonDir = "../preop/WebContent/json/center/";
		convertXmlFileDir(xmlDir,jsonDir);

	}
	
	private static void convertXmlFileDir(String xmlDir, String jsonDir){
		String xmlFile = "";
		String[] xmlFiles = getXmlFiles(xmlDir); 
		for (int i = 0; i != xmlFiles.length; i++) {
			xmlFile = xmlFiles[i];
			try {
				convertXml(xmlFile, xmlDir, jsonDir);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static String[] getXmlFiles(String xmlDir){
		File dir = new File(xmlDir);
		String[] children = dir.list();
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.endsWith(".xml");
			}
		};
		children = dir.list(filter);
		return children;
	}
	
	
	private static void convertXml(String xmlFile, String xmlDir, String jsonDir) throws IOException {
		XMLSerializer xmlSerializer = new XMLSerializer();
		InputStream is = new FileInputStream(xmlDir + xmlFile);
		JSON json = xmlSerializer.readFromStream(is);

		boolean exists = (new File(jsonDir + xmlFile + ".json")).exists();
		boolean success = false;
		
		File jsonFile = new File(jsonDir + xmlFile + ".json");
		if(!exists){
			success = jsonFile.createNewFile();
		} else {
			success = true;
		}
		
		if (success) {
			BufferedWriter out = new BufferedWriter(new FileWriter(jsonFile));
			out.write(json.toString(2));
			out.close();
		}
	}

}
